package com.scs.application.modules.sys.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.threadLock.ThreadLock;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.entity.ScheduleJob;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.service.ScheduleJobService;
import com.scs.application.modules.thirdparty.core.MscmHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 定时任务 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/sys/schedule_job")
public class ScheduleJobController extends CrudController<ScheduleJobService, ScheduleJob>{


    @PostMapping("/stopAll")
    public RestResult stopAll() {
        service.stopAll(true);
        return RestResult.ok("停止定时器成功", null);
    }

    @PostMapping("/startAll")
    public RestResult startAll() {
        service.startAll(true);
        return RestResult.ok("启动定时器成功", null);
    }


    @PostMapping("/resume/{id}")
    public RestResult resume(@PathVariable(value = "id") String id) {

        ScheduleJob scheduleJob = service.getById(id);
        if (scheduleJob == null) {
            return RestResult.error("恢复作业失败", null);
        }
        service.resume(scheduleJob);

        return RestResult.ok("恢复作业成功", null);
    }

    @PostMapping("/cronTime")
    public RestResult cronTime(@RequestBody Map<String, Object> para) {
        String cronExpression = (String) para.get("cronExpression");

        List<String> strings = service.fiveCronTime(cronExpression);

        return RestResult.ok("解析成功", strings);
    }


    @PostMapping("/pause/{id}")
    public RestResult pause(@PathVariable(value = "id") String id) {

        ScheduleJob scheduleJob = service.getById(id);
        if (scheduleJob == null) {
            return RestResult.error("暂停作业失败", null);
        }
        service.pause(scheduleJob);
        return RestResult.ok("暂停作业成功", null);
    }

    @PostMapping("/runOnce/{id}")
    public RestResult runOnce(@PathVariable(value = "id") String id) {
        synchronized (id.intern()) {
            ScheduleJob scheduleJob = service.getById(id);
            if (scheduleJob == null) {
                return RestResult.error("运行作业失败,该任务已被移除", null);
            }
            return RestResult.ok(service.runOnce(scheduleJob), null);
        }
    }

    @GetMapping("/isRunning")
    public RestResult isRunning() {
        return RestResult.ok("查询成功", Collections.singletonMap("isRunning", service.isRunning()));
    }



    @PostMapping("/execMore")
    /**
    * @Description： 批量执行
    */
    @ThreadLock(busType = "execMore")
    public RestResult execMore(@RequestBody Map<String, String> para) {
        String[] ids = para.get("ids").split(",") ;
        List<String> returnMsg = new ArrayList<String>();
        ScheduleJob scheduleJob;
        String runMsg;
        for (int i =0 ; i <ids.length ;i ++) {
            scheduleJob = service.getById(ids[i]);
            try {
                if (scheduleJob == null) throw  new BusinessException("未找到定时任务，id=%s",ids[0]);
                runMsg=service.runOnce(scheduleJob);
            }catch (Exception e) {
                runMsg = e != null ? e.getMessage() : "未知异常";
            }
            returnMsg.add("任务名称："+scheduleJob.getJobName()+"，"+runMsg);
        }

        return RestResult.ok("批量执行结束<br>"+ StringUtils.join(returnMsg,"<br>"));
    }

    /**
     * 清除MSCM的Token
     * @return
     */
    @PostMapping("/clearMscmToken")
    public RestResult clearMscmToken() {
        MscmHolder.cleanToken();
        return RestResult.ok("清除成功");
    }


    /**
    * @Description： 根据目标字符串执行
    */
    @GetMapping("/runOnceByInvokeTarget/{invokeTarget}")
    public RestResult runOnceByInvokeTarget(@PathVariable(value = "invokeTarget") String invokeTarget) {
        ScheduleJob scheduleJob = service.getOne(Wrappers.<ScheduleJob>query().like("invoke_target",invokeTarget));
        if (scheduleJob == null) {
            return RestResult.error("运行作业失败,该任务已被移除", null);
        }
        return RestResult.ok(service.runOnce(scheduleJob), null);
    }

    /**
     * @Description： 批量禁用
    */
    @PostMapping("/disabledBatch")
    public RestResult disabledBatch(@RequestBody Map<String, String> para) {
        String[] ids = para.get("ids").split(",") ;
        service.update(Wrappers.<ScheduleJob>update().set("flag_enabled", GlobalConsts.NO).in("id",ids ));
        return RestResult.ok();
    }

    /**
     * @Description： 批量启用
    */
    @PostMapping("/enabledBatch")
    public RestResult enabledBatch(@RequestBody Map<String, String> para) {
        String[] ids = para.get("ids").split(",") ;
        service.update(Wrappers.<ScheduleJob>update().set("flag_enabled", GlobalConsts.YES).in("id",ids ));
        return RestResult.ok();
    }

}
